<?php
namespace Utils;

/**
 * 数据库连接类
 */
class Database {
    private static $instance = null;
    private $connection = null;
    
    /**
     * 私有构造函数，防止外部实例化
     */
    private function __construct() {
        $config = require __DIR__ . '/../../config/database.php';
        
        try {
            $dsn = sprintf(
                "mysql:host=%s;dbname=%s;charset=%s;port=%d",
                $config['host'],
                $config['database'],
                $config['charset'],
                $config['port']
            );
            
            $this->connection = new \PDO(
                $dsn,
                $config['username'],
                $config['password'],
                [
                    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
                ]
            );
        } catch (\PDOException $e) {
            throw new \Exception("数据库连接失败: " . $e->getMessage());
        }
    }
    
    /**
     * 获取数据库实例
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * 获取PDO连接
     */
    public function getConnection() {
        return $this->connection;
    }
    
    /**
     * 执行SQL查询
     */
    public function query($sql, $params = []) {
        try {
            $stmt = $this->connection->prepare($sql);
            $stmt->execute($params);
            return $stmt;
        } catch (\PDOException $e) {
            throw new \Exception("SQL执行错误: " . $e->getMessage());
        }
    }
} 